import React from "react";
import styles from "./PostListPage.module.css";
import { Button, Empty, Typography } from "antd";
import { History } from "history";
import { match } from "react-router-dom";
import PostAuthor from "./component/PostAuthor";
import ReactionButtons from "./component/ReactionButtons";
import { useSelector } from "react-redux";

interface Props {
    history: History;
    match: match<{ id: string }>;
}
/**
 * 帖子详情
 * */
const PostDetailPage = ({ history, match }: Props) => {
    const data = useSelector((state: any) => {
        console.log("posts:", state);

        const { posts } = state;
        const { params } = match;
        if (posts.list && params) {
            for (let i = 0; i < posts.list.length; i++) {
                const item = posts.list[i];
                if (String(item.id) === params.id) {
                    return { ...item };
                }
            }
        }
        return null;
    });
    const onEdit = () => {
        if (data) {
            const path = `/editPost/${data.id}`;
            history.push(path, data);
        }
    };
    const goBack = () => {
        history.goBack();
    };

    return (
        <div className={styles.main}>
            <Typography.Title level={3}>
                帖子详情
                <Button onClick={goBack} type={"link"}>
                    返回
                </Button>
            </Typography.Title>

            {data ? (
                <div>
                    <Typography.Title level={4}>{data?.title}</Typography.Title>
                    <Typography.Paragraph>
                        <PostAuthor userId={data?.author} />
                        发布于{data.date}
                    </Typography.Paragraph>
                    <Typography.Paragraph>{data?.content}</Typography.Paragraph>
                    <ReactionButtons data={data} />
                    <Button onClick={onEdit} type={"primary"}>
                        编辑
                    </Button>
                </div>
            ) : (
                <Empty />
            )}
        </div>
    );
};

export default PostDetailPage;
